package com.zhihaoliang.coroutine.buss.channel.func

import com.zhihaoliang.coroutine.util.log
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.cancelChildren
import kotlinx.coroutines.channels.ReceiveChannel
import kotlinx.coroutines.channels.produce
import kotlinx.coroutines.launch

/**
 * @author 支豪亮
 * @date 2022/10/27 17:11
 * @des 只是一个查找素数的demo
 */
object PrimeFinder {
    @OptIn(ExperimentalCoroutinesApi::class)
    fun CoroutineScope.numberProducer(start: Int) = produce<Int> {
        var index = start
        while (true) send(index++)
    }

    @OptIn(ExperimentalCoroutinesApi::class)
    fun CoroutineScope.filter(numbers: ReceiveChannel<Int>, prime: Int) = produce<Int> {
        for (x in numbers) if (x % prime != 0) send(x)
    }

    fun findPrime(mainScope: CoroutineScope) = mainScope.launch {
        var cur = numberProducer(2)
        repeat(10) {
            val prime = cur.receive()
            log(prime)
            cur = filter(cur, prime)
        }
        coroutineContext.cancelChildren()
    }
}